import re

from rest_framework import serializers

from apps.users.models import User


class UserSerializer(serializers.ModelSerializer):
    """
    用户表序列化器
    """
    class Meta:
        # 指定生成序列化器的模型类
        model = User
        # 指定字段
        fields = ('id','username','email','mobile','password')
        extra_kwargs = {
            'password': {
                'write_only':True,
                'max_length':20,
                'min_length':8,
            },
            'username':{
                'max_length': 20,
                'min_length': 5,
            }

        }
    # 手机号验证
    def validate_mobile(self, attrs):
        if not re.match(r'1[3-9]\d{9}',attrs):
            return serializers.ValidationError('手机格式错误')

        # 唯一值判断
        try:
            user = User.objects.get(mobile=attrs)
        except:
            return None
        if user:
            raise serializers.ValidationError('手机号已经存在')
        return attrs

    # 密码加密入库
    def create(self, validated_data):
        # 重写create方法对密码进行加密保存
        # 第一种 先调用父类方法获取保存后的用户对象
        # user = super().create(validated_data)
        # 对用户对象中的password进行加密
        # user.set_password(validated_data['password'])
        # user.save()
        # 第二种直接进行密码加密保存{name:python} name = python
        user = User.objects.create_user(**validated_data)
        return user